package com.trip.wechat.platform.subsystem.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.trip.wechat.platform.model.AccessTokenBO;
import com.trip.wechat.platform.subsystem.AccessTokenFacade;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.StringJoiner;

/**
 * 功能说明: 微信平台 - AccessToken实现<br>
 * 系统说明: <br>
 * 模块说明: <br>
 * 功能描述: <br>
 */
@Component("mp.accessToken")
public class AccessTokenFacadeMPImpl implements AccessTokenFacade {

    final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Value("${mp.access_token.url:https://api.weixin.qq.com/cgi-bin/token}")
    protected String accessTokenUrl;

    @Autowired
    OkHttpClient httpClient;

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public AccessTokenBO fetchAccessToken(String appId, String appSecret, String publicKey) {
        if (Strings.isNullOrEmpty(appId) || Strings.isNullOrEmpty(appSecret)) {
            LOGGER.warn("[mp.accessToken.fetchAccessToken] appId or appSecret cannot be empty!");
//            return createResult(CodeDict.C_SERVICE_FAIL, "appId or appSecret is empty");
        }

        StringJoiner joiner = new StringJoiner("&", "?", "");
        //grant_type=client_credential&appid=APPID&secret=APPSECRET
        joiner.add(Joiner.on("=").join("grant_type", "client_credential"));
        joiner.add(Joiner.on("=").join("appid", appId));
        joiner.add(Joiner.on("=").join("secret", appSecret));

        try {
            String url = accessTokenUrl + joiner.toString();
            LOGGER.info("[mp.accessToken.fetchAccessToken] request => {}", url);
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
            Response response = httpClient.newCall(request).execute();

            String responseBody = response.body().string();
            LOGGER.info("[mp.accessToken.fetchAccessToken] response => {}", responseBody);
            return objectMapper.readValue(responseBody, AccessTokenBO.class);

        } catch (IOException e) {
            LOGGER.warn("[mp.accessToken.fetchAccessToken] failed! IOException! {}", e.getMessage());
//            return createResult(CodeDict.C_SERVICE_FAIL, "fetch token failed! IOException!");
        } catch (Exception e) {
            LOGGER.warn("[mp.accessToken.fetchAccessToken] failed! {}! {}", e.getClass().getName(), e.getMessage());
//            return createResult(CodeDict.C_SERVICE_FAIL, "fetch token failed!");
        }
        return null;
    }

    protected AccessTokenBO createResult(int code, String message) {
        AccessTokenBO resultBO = new AccessTokenBO();
        resultBO.setErrcode(code);
        resultBO.setErrmsg(message);
        return resultBO;
    }
}
